/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.welchapps.nporganizer;

//import org.apache.commons.net.ftp.*;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import com.welchapps.nporganizer.NotePad.DataCount;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQueryAdapter;
import com.parse.ParseQueryAdapter.QueryFactory;
import com.welchapps.nporganizer.NotePad.NoteColumns;

/**
 * Displays a list of notes. Will display notes from the {@link Uri}
 * provided in the intent if there is one, otherwise defaults to displaying the
 * contents of the {@link NoteProvider}
 */
public class NotesList extends Activity {
    private static final String TAG = "NotesList";
    private static final String version = "0.5.2";
    //private static final String def_title = "Nail Polish Organizer";
    private int currentPosition;
    protected ListView rowlist;
    private TextView totalCount, filterBy;
	private FTPClient ftpClient;
	private Context context;
	private boolean filtered;
	protected String line;
	public static ParseQuery<ParseObject> query;

    /**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
        NoteColumns._ID, // 0
        NoteColumns.NAME, // 1
        NoteColumns.BRAND, // 2
        NoteColumns.COLLECTION, // 3
        NoteColumns.COLOR, // 4
        NoteColumns.FINISH, // 5
        NoteColumns.STATUS, // 6
        NoteColumns.ADDNOTE, // 7
        NoteColumns.IMG // 8
    };
  
    
    // Need handler for callbacks to the UI thread
    final Handler mHandler = new Handler();

    // Create runnable for posting
    final Runnable mUpdateNeeded = new Runnable() {
        public void run() {
        	AlertDialog.Builder builder = new AlertDialog.Builder(context);
        	builder.setTitle("New Version Available");
        	builder.setMessage("Download version "+line+" from:\n"+
        			"https://sites.google.com/site/welchapps/");
	        builder.setPositiveButton("Ok", new OnClickListener() {
	                public void onClick(DialogInterface dialog, int arg1) {
	                    dialog.dismiss();
	                }});
	        builder.setNegativeButton("Open Page", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                	Intent intent = new Intent();
                	intent.setAction(Intent.ACTION_VIEW);
        			intent.setData(Uri.parse("https://sites.google.com/site/welchapps/nail-polish-organizer"));
        			startActivity(intent);
                }});
	        builder.create().show();
        }
    };
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        context = this;
        setContentView(R.layout.noteslist);
        rowlist = (ListView) findViewById(R.id.rowlist);
        totalCount = (TextView) findViewById(R.id.totalCount);
        filterBy = (TextView) findViewById(R.id.FilterBy);
        
        // Create parse instance
    	Parse.initialize(context, "paKVisD4pA6AeWne5Lo3n50280UdzgM9FpwME9FE", "5RKs9paYJ4SNacYlEoKWiyU9kLIVd5RP15gUokVz");
        
        //setup settings
        final String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
    	SharedPreferences settings = getSharedPreferences("defSettings",0);
    	final Integer runs = settings.getInt("runs",0);
    	SharedPreferences.Editor editor = settings.edit();
    	if (!settings.getString("version",version).equals(version)) {updateWelcome();}
		editor.putString("version", version);
    	editor.putInt("runs",runs+1);
    	if(settings.getString("id_key","null").equals("null")) editor.putString("id_key", android_id);
    	editor.commit();
    	
        // If no data was given in the intent (because we were started
        // as a MAIN activity), then use our default content provider.
        Intent intent = getIntent();
        final String action = intent.getAction();
        if (intent.getData() == null || Intent.ACTION_VIEW.equals(action)) {
            intent.setData(NoteColumns.CONTENT_URI);
        }

        //check for correct version and new import
        updateCheck();
        
    	
    	// Alert to start requery
    	NotePad.Requery = true;

    }
    
    @Override
    protected void onResume() {
        super.onResume();   
        
        // Check if a requery is needed
        if (NotePad.Requery) {
        	final SharedPreferences defsettings = PreferenceManager.getDefaultSharedPreferences(context);
	        SharedPreferences filtersettings = getSharedPreferences("filterPref",0);
	        final String value = filtersettings.getString("value","");      
	        final String cat = filtersettings.getString("category","None");  
	        final String status = filtersettings.getString("status","All Polishes");	
	    	filterBy.setText("");
	    	
	    	if((!cat.equals("None") && !value.equals("")) || !status.equals("All Polishes")){
	        	filtered = true;
	    	}
	    	else {
	        	filtered = false;      		
	    	}
	    	//Reset options menu for new icon
	    	invalidateOptionsMenu();
	    	if(!cat.equals("None") && !value.equals("")) {
	    		filterBy.setText(cat + ": " + value);
	    	}
	    	
	        DataCount.reset();
	        // Used to map notes entries from the database to views
	        Log.i(TAG,"Creating Query Factory");
	    	QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
	        		    public ParseQuery<ParseObject> create() {
	        		      // Configure ParseQuery for sort order and filter
	        		      ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("nailPolish");
	        		      if (!cat.equals("None") && !value.equals("")){
	        		    	  query.whereEqualTo(cat.toLowerCase(), value);
	        		      }
	        		      if (!status.equals("All Polishes")){
	        		    	  query.whereEqualTo("status", status);
	        		      }
	        		      query.orderByAscending(defsettings.getString("sort_order", "name"));
	        		      query.setLimit(1000);
	        		      query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
	        		      return query;
	        		    }
	        		  };
	        Log.i(TAG,"Creating Cursor Adapter");
	        final MyCursorAdapter adapter = new MyCursorAdapter(this, factory);
	        adapter.setPaginationEnabled(false);
	        adapter.setObjectsPerPage(1000);
	        rowlist.setAdapter(adapter);
	    	// setup listener for list clicking
	        Log.i(TAG,"Setting up row listener");
	        rowlist.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					Uri noteUri = getIntent().getData();
					
	                String action = getIntent().getAction();
	                if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
	                    // The caller is waiting for us to return a note selected by
	                    // the user.  The have clicked on one, so return it now.
	                    setResult(RESULT_OK, new Intent().setData(noteUri));
	                } else {
	                	Intent Editor = new Intent(Intent.ACTION_EDIT); //, noteUri); 
	                	Editor.putExtra("item", arg3);
	                	Editor.putExtra("uri", noteUri);
	                	Editor.putExtra("id", adapter.getItemId((int) arg3));
	                	// Editor.setData(getIntent().getData());
	                    // Launch activity to view/edit the currently selected item
	                	startActivity(Editor);
	                }
				}
	            
	        });
	        Log.i(TAG,"Creating Query from factory");
	        
			query = factory.create();
			// Setup IDs
			 query.findInBackground(new FindCallback<ParseObject>() {
			     public void done(List<ParseObject> objects, ParseException e) {
			         if (e == null) {
			        	 rowlist.setSelection(currentPosition);
			        	 Log.i(TAG, "Objects retrieved: " + Integer.toString(objects.size()));
				    	 NotePad.objects = objects;
				    	 totalCount.setText("Total Count: " + Integer.toString(objects.size()));
			         } else {
			    	 	Log.e(TAG, "Failed to get objects: ", e);
			         }
			     }
			 });
			 
			 // Notify query is done
			 NotePad.Requery = false;
        }
        
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        currentPosition = rowlist.getFirstVisiblePosition();
    }   
    
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate menu from XML resource
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.list_options_menu, menu);
        


        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { 
    	SharedPreferences settings = getSharedPreferences("defSettings",0);
    	boolean web = settings.getBoolean("web_sync",false);
        switch (item.getItemId()) {
        case R.id.menu_add:
        	addItem(null);
        	return true;
        case R.id.menu_filter:
        	filterItem(null);
        	return true;
        case R.id.menu_settings:
        	startActivity(new Intent(this, QuickPrefsActivity.class));
        	return true;
        case R.id.menu_about:
        	showAbout(this);
        	return true;
        case R.id.menu_signup:
        	startActivity(new Intent(this, Login.class));
        	return true;
        default: 
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
	public boolean onContextItemSelected(MenuItem item) {
	    AdapterView.AdapterContextMenuInfo info;
	    try {
	         info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
	    } catch (ClassCastException e) {
	        Log.e(TAG, "bad menuInfo", e);
	        return false;
	    }
	    
	    Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id);
	
	    switch (item.getItemId()) {
	    case R.id.context_open:
	        // Launch activity to view/edit the currently selected item
	        startActivity(new Intent(Intent.ACTION_EDIT, noteUri));
	        return true;
	    case R.id.context_delete:
	        // Delete the note that the context menu is for
	        getContentResolver().delete(noteUri, null, null);
	        return true;
	    default:
	        return super.onContextItemSelected(item);
	    }
	}

    @Override
    public boolean onPrepareOptionsMenu(Menu menu){
        MenuItem menu_filter = menu.findItem(R.id.menu_filter);
        if (filtered == false){
       	 menu_filter.setIcon(R.drawable.collections_sort_off);
        }else{
       	 menu_filter.setIcon(R.drawable.collections_sort_on);
        }    	
		return true;
    	
    }
    
    
    private void updateWelcome(){
    	AlertDialog.Builder builder = new AlertDialog.Builder(context);
    	builder.setTitle("Version: "+version);
    	builder.setMessage("This update added the ability to create a swap list.");
        builder.setPositiveButton("Ok", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                	dialog.dismiss();
                }});
        builder.create().show();
    }
    
	private void updateCheck(){
    	new Thread(){
    		public void run(){
    			//setup settings
    	    	SharedPreferences settings = getSharedPreferences("defSettings",0);
    	    	final boolean update = settings.getBoolean("update_notify",true);
    	    	final boolean autosync = settings.getBoolean("auto_sync",true);
    			//check for update
    	    	if (update){
	    	        try {     
	    				URLConnection Url = new URL("https://sites.google.com/site/welchapps/version.txt").openConnection();
	    				BufferedReader reader = new BufferedReader(new InputStreamReader(Url.getInputStream(), "UTF-8")); 
	    				line = reader.readLine();
	
	    				if (!line.equals(version)) mHandler.post(mUpdateNeeded);
	    					
	    			} catch (MalformedURLException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			} catch (UnsupportedEncodingException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			} catch (IOException e) {
	    				// TODO Auto-generated catch block
	    				e.printStackTrace();
	    			}
    	        }
    		}
    		
    	}.start();

    }
    
    public void addItem(View view){
    	startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
    }
    
    public void showAbout(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("About");
        builder.setMessage("Version: "+version+"\n\n"+
        		"Written by Eric Welch for his nail polish addicted girlfriend\n\n"+
        		"ericwelch08@gmail.com\n\n"+ getText(R.string.features) + "\n" + 
        		getText(R.string.instructions));
        builder.setPositiveButton("Close", new OnClickListener() {
                public void onClick(DialogInterface dialog, int arg1) {
                    dialog.dismiss();
                }});
        builder.setNegativeButton("Visit Website", new OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
            	Intent intent = new Intent();
            	intent.setAction(Intent.ACTION_VIEW);
    			intent.setData(Uri.parse("https://sites.google.com/site/welchapps/nail-polish-organizer"));
    			startActivity(intent);
            }});
        builder.setCancelable(false);
        builder.create().show();
    }
    
    public void filterItem(View view){
    	startActivity(new Intent(this, FilterList.class));
    }
	
}




